package login

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	hutil "hh/practice/highproc"
	"net/http"
)

type MiddlewareBuilder struct {
}

func (m *MiddlewareBuilder) CheckLogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		if !isNeedToLogin(c.Request.URL.Path) {
			return
		}
		sess := sessions.Default(c)
		if sess.Get("userId") == nil {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}
	}
}

func isNeedToLogin(path string) bool {
	paths := []string{"/users/login", "/users/signup"}

	return hutil.Every(paths, func(s string) bool {
		return path != s
	})
}
